package org.xiaoleng.igateway.security;

import io.jsonwebtoken.*;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.security.Keys;
import jakarta.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.security.Key;
import java.util.Date;

@Component
public class TokenProvider {

    private JwtParser jwtParser;
    private JwtBuilder jwtBuilder;

    @Value("${jwt.secret}")
    private String jwtSecret;

    @Value("${jwt.token-validity-in-seconds}")
    private long expire;

    public static final String AUTHORITIES_KEY = "user";
    public static final String APP_AUTHORITIES_KEY = "app_user";

    @PostConstruct
    public void init() {
        byte[] keyBytes = Decoders.BASE64.decode(jwtSecret);
        Key key = Keys.hmacShaKeyFor(keyBytes);
        jwtParser = Jwts.parserBuilder()
                .setSigningKey(key)
                .build();
        jwtBuilder = Jwts.builder()
                .signWith(key, SignatureAlgorithm.HS512);
    }

    public String createToken(UserInfo userInfo) {
        return this.jwtBuilder.claim(AUTHORITIES_KEY, userInfo.getUserName())
                .setSubject(userInfo.getUserName())
                .compact();
    }

    public String createAppToken(UserInfo userInfo) {
        return this.jwtBuilder.claim(APP_AUTHORITIES_KEY, userInfo.getUserName())
                .setSubject(userInfo.getUserName())
                .compact();
    }

    public boolean validateToken(String token) {
        try {
            this.jwtParser.parseClaimsJws(token).getBody();
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    public String parseToken(String token) {
        Claims claims = this.jwtParser.parseClaimsJws(token)
                .getBody();
        return claims.getSubject();
    }


}
